package org.leetcode.easy;


import java.util.HashMap;
import java.util.Map;

public class MajorityElement {
    public int majorityElement(int[] nums) {
        Map<Integer, Integer> countMap = new HashMap<>();

        for (int num : nums) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);

            // 当某个元素的计数超过n/2时，直接返回该元素
            if (countMap.get(num) > nums.length / 2) {
                return num;
            }
        }

        throw new IllegalArgumentException("No majority element found in the array.");
    }

    // 测试例子
    public static void main(String[] args) {
        MajorityElement solution = new MajorityElement();
        int[] nums1 = {3, 2, 3};
        System.out.println(solution.majorityElement(nums1));  // 输出: 3

        int[] nums2 = {2, 2, 1, 1, 1, 2, 2};
        System.out.println(solution.majorityElement(nums2));  // 输出: 2
    }
}

